package com.voodoo.lib_frame.manager;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Process;

import com.voodoo.lib_frame.FrameApplication;
import com.voodoo.lib_utils.L;

import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.Stack;

/**
 * Author: voodoo
 * CreateDate: 2019/08/29 029 下午 09:47:30
 * Description: Activity管理类
 */
public class FActivityManager {

    private Stack<WeakReference<Activity>> activitys;
    private static FActivityManager activityManager;

    public static FActivityManager getInstance() {
        if (activityManager == null) {
            synchronized (FActivityManager.class) {
                if (activityManager == null) {
                    activityManager = new FActivityManager();
                }
            }
        }
        return activityManager;
    }

    /**
     * 将Activity添加到栈中
     *
     * @param activity 目标Activity
     */
    public void addActivity(WeakReference<Activity> activity) {
        if (activitys == null) {
            activitys = new Stack<>();
        }
        activitys.push(activity);
    }

    /**
     * 获得栈中最顶层的Activity
     *
     * @param context
     * @return
     */
    @SuppressLint("NewApi")
    public Activity getTopActivity(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        String activityName = am.getRunningTasks(1).get(0).topActivity.getClassName();
        Class clS = null;
        try {
            clS = Class.forName(activityName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            return (Activity) clS.newInstance();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 获取栈顶Activity
     *
     * @return 栈顶的Activity
     */
    public Activity getTopActivity() {
        if (activitys.lastElement().get() == null) {
            L.i("获取 Stack 1 栈顶aty"+activitys.lastElement().get());
            return getTopActivity(FrameApplication.getFrameContext());
        }
        L.i("获取 Stack 2 栈顶aty"+activitys.lastElement().get());
        return activitys.lastElement().get();
    }


    /**
     * 结束指定的Activity
     */
    public void killActivity(Activity activity) {
        if (activity != null) {
//            L.i("删除关闭 Stack 中的  aty",activity.getComponentName());
            activity.finish();
        }
    }

    /**
     * 销毁栈顶之外其他的Activity（保留栈顶的Activity）
     */
    public void killOtherActivity() {
        int i = 0;
        int count = activitys.size() - 1;
        try {
            while (i < count) {
                L.i("获取 Stack  栈 大小", count, i, activitys.get(i).get().getLocalClassName());
                killActivity(activitys.get(i).get());
                activitys.remove(i);
                i++;
            }
        } catch (Exception e) {
            L.i("获取 Stack  Exception", e.getMessage());
        }


    }

    /**
     * 结束指定类名的Activity
     *
     * @param cls Class
     */
    public void killActivity(Class<?> cls) {
        Iterator<WeakReference<Activity>> iterator = activitys.iterator();
        while (iterator.hasNext()) {
            Activity activity = iterator.next().get();
            if (activity.getClass().equals(cls)) {
                L.i("栈killActivity == " +activity.getLocalClassName());
                iterator.remove();
                killActivity(activity);
            }
        }

//        L.i("获取 Stack  栈 大小",activitys.size());
    }

    public int getStackSize() {

        if (activitys != null) {
            for (int i = 0, size = activitys.size(); i < size; i++) {
                if (null != activitys.get(i)) {
                    L.i("栈activity == " +activitys.get(i).get().getLocalClassName());
                }
            }

            return activitys.size();
        }
        return 0;
    }

    /**
     * 结束所有Activity并退出程序
     */
    public void killAllActivityExit() {
        for (int i = 0, size = activitys.size(); i < size; i++) {
            if (null != activitys.get(i)) {
                activitys.get(i).get().finish();
            }
        }
        activitys.clear(); // 清除栈
        Process.killProcess(Process.myPid()); // 结束当前程序进程
        System.exit(0); // 销毁虚拟机
    }

}
